<!-- 注册
 1. vue始终在用双向绑定的思想来准备前后端交互，每一个vue都会定义好变量给 表单（form）或者表格（table）中的html元素的值绑定
-->
<template>
  <div><!-- element组件库的Dialog对话框默认可以通过点击 modal 关闭 Dialog，即点击空白处弹框可关闭。 -->
    <!-- :visible.sync 子组键改变父组件的值 控制子组件的显示-->
    <el-dialog title="标题名" :visible.sync="editDialogIsShow" :before-close="handleClose" :close-on-click-modal="false">
      <!--图片上传开始-->
      <el-form label-width="120px" ref="editRestaurantUploadForm">
        <!-- 代码中的1表示第几个 和引入js的type变量对应 -->
        <el-form-item label="饭店照片">
          <el-upload
            class="upload"
            :action="getUploadUrl"
            list-type="picture-card"
            :limit="1"
            accept="image/*"
            :on-change="(file,fileList)=>{imgHandleChange(file,fileList,1,this,'editRestaurantUploadForm','restaurant')}"
            :on-remove="(file,fileList)=>{imgHandleRemove(1,this)}"
            :on-before="(file,fileList)=>{imghandleBeforeUpload(file,1,this)}"
            :auto-upload="false"
            :file-list="fileList"
            ref="file1">
            <i class="el-icon-plus"></i>
          </el-upload>
          <!--<viewer-dialog ref="viewer" :images="imagesUp"></viewer-dialog>-->
        </el-form-item>
        <!-- 图片上传结束-->
        <!-- 上传多张照片开始-->
        <el-form label-width="120px" ref="addTeacherUploadForm">
          <!-- 代码中的1表示第几个 和引入js的type变量对应 -->
          <el-form-item label="店铺照片详情">


            <el-upload class="upload-demo" ref="upload"
                       action="getUploadUrl"
                       list-type="picture-card"
                       :limit="3"
                       name="file"
                       :multiple="true"
                       :on-preview="handlePreview"
                       :on-remove="handleRemove"
                       :file-list="fileLists"
                       :auto-upload="false"
                       :http-request="uploadFiles"
            >
              <i class="el-icon-plus"></i>

            </el-upload>
            <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传</el-button>
          </el-form-item>
        </el-form>
        <!-- 上传多张照片结束-->
      </el-form>
      <el-form :model="restaurant" label-width="80px" :rules="editRestaurantRules" ref="editRestaurantForm">
<!--        <el-form-item label="营业执照" prop="rbus">-->
<!--          <el-col :span="8">-->
<!--            <el-input v-model="restaurant.rbus"></el-input>-->
<!--          </el-col>-->
<!--        </el-form-item>-->
        <el-form-item label="营业执照等级">
          <el-col :span="3">
            <el-select v-model="restaurant.rbus" placeholder="请选择">
              <el-option v-for="(rbusgroup,index) in allRestaurantGroupABC" :key="rbusgroup.num"
                         :label="rbusgroup.restaurantName" :value="rbusgroup.restaurantName"/>
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item label="饭店名称" prop="rname">
          <el-col :span="8">
            <el-input v-model="restaurant.rname"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="电话号码" prop="rphone">
          <el-col :span="8">
            <el-input v-model="restaurant.rphone"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="地址" prop="riddr">
          <el-col :span="8">
            <el-input v-model="restaurant.riddr"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="邮箱" prop="remail">
          <el-col :span="8">
            <el-input v-model="restaurant.remail" placeholder="请填入邮件" @input="updateView($event)" clearable />
          </el-col>
        </el-form-item>
        <el-form-item label="状态">
          <el-col :span="3">
            <el-select v-model="restaurant.rstate" placeholder="请选择">
              <el-option v-for="(restaurantgroup,index) in allRestaurantGroup" :key="restaurantgroup.num"
                         :label="restaurantgroup.restaurantName" :value="restaurantgroup.restaurantName"/>
            </el-select>
          </el-col>
        </el-form-item>
      </el-form>
      <span>
      <el-button type="success" @click="editRestaurant('editRestaurantForm')">修改</el-button>
    </span>
    </el-dialog>
  </div>
</template>

<script>
  import rules from "../../../../static/js/validator/rules.js"
  import api from "../../../../axios/api";
  import utils from "../../../../static/js/utils/upload.js"

  export default {
    name: "editRestaurant",
    data() {
      return {
        oldImg: false,
        //上传使用
        fileList: [], //缓存区文件
        uploadFile: [], //  上传用文件
        formData: {files: []},
        imagesUp: null,
        //上传使用结束
        //多图片上传
        fileLists: [],
        formDatas: "",
        //多图片上传结束
        restaurant: {rname: "", rimg: "", rstate: "", rid: "", rpwd: "", rcal: "",riddr:""},
        editDialogIsShow: false,
        allRestaurantGroup: [{num: 0, "restaurantName": "营业"}, {num: 1, "restaurantName": "打烊"}],
        allRestaurantGroupABC: [{num: 0, "restaurantName": "A+"}, {num: 1, "restaurantName": "A"}, {num: 2, "restaurantName": "A-"},
          {num: 3, "restaurantName": "B+"}, {num: 4, "restaurantName": "B"}, {num: 5, "restaurantName": "B-"},
          {num: 6, "restaurantName": "C+"}, {num: 7, "restaurantName": "C"}, {num: 8, "restaurantName": "C-"}
        ],
        editRestaurantRules: {
          rname: [{required: true, message: "饭店名称不能为空", trigger: 'blur'},
            {max: 20, min: 2, message: '长度异常 长度在2-20之间', trigger: 'blur'}, {
              pattern: /^[\u0391-\uFFE5A-Za-z]+$/,
              message: '饭店名称必须为中文',
              trigger: 'blur'
            }],
          rphone: [{required: true, message: "电话不能为空", trigger: 'blur'},{trigger:'blur',validator:rules.FormValidate.Form().validatePhone}],
          rbus:[{required:true,message:"营业执照不能为空",trigger:'blur'},{max:20,min:1,message:'长度异常 长度在2-20之间',trigger:'blur'}],
          remail:[{required:true,message:"邮件不能为空",trigger:'blur'},{trigger:'blur',validator:rules.FormValidate.Form().validateEmail}],
          riddr:[{required: true, message: "地址不能为空", trigger: 'blur'},{required: true, pattern: /^[\u4e00-\u9fa5_a-zA-Z0-9.·-]+$/, message: '名字不支持特殊字符', trigger: 'blur'}]
        }
      }
    },
    methods: {
      getImgUrl: function (rimg) {
        return this.$store.state.host + "/upload/images/head/" + rimg;
      },
      editRestaurant: function (editRestaurantForm) {
        this.$refs[editRestaurantForm].validate(valid => {//此处refs对象和标签上的ref对应
          if (valid) {
            //如果通过验证 to do...
            // console.log(this.restaurant);
            // alert(this.restaurant.rname+"编辑成功");
            //alert(111);
            //调取api方法请求后端方法进行修改
            console.log(this.restaurant);
            this.setDataFromAxios();
            this.$message.success("修改成功")
            this.handleClose();
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      init(restaurant) {
        this.fileList = [] //缓存区文件
        this.uploadFile = [],
         this.editDialogIsShow = true;
        this.restaurant = restaurant;
        console.log(restaurant);
        if (this.restaurant.rimg != null && this.restaurant.rimg != '') {

          let urls = this.restaurant.rimg;
          let fileObj = {};
          fileObj.name = "file";
          fileObj.url = this.$store.state.host + "/upload/images/restaurant/" + urls;
          console.log(fileObj.url);
          this.fileList.push(fileObj);
          this.oldImg = true;
        }
      },


      //关闭页面
      handleClose() {
        this.editDialogIsShow = false;
        //给父组件传参
        this.$emit("editDialogIsShow", this.editDialogIsShow);
      },
      setDataFromAxios: function () {
        alert(this.$store.state.host);
        console.log(this.restaurant);
        api.setDataFromAxios(this.$store.state.host + "restaurantController/updateRestaurantByRno", this.restaurant, "post")
          .then(res => {
            this.oldImg = false;
            this.$message.info("上传图片成功!");
            this.leagues = res.leagues
            //为什么要封装一下方法 1.每个vue组件有自己的一些参数处理，简化调用本来这个setDataFromAxios这个方法属于api 重新封装就属于当前页面
          });//.then方法 就是当服务器有返回的时候执行回调函数，对比jquery的ajax success:function（data）
      },
      imghandleBeforeUpload(file, type, vm) {

        return utils.UPLOAD.Upload().handleBeforeUpload(file, type, vm);
      },
      imgHandleChange(file, fileList, type, vm, modelName, name) {

        return utils.UPLOAD.Upload().handleChange(file, fileList, type, vm, modelName, name);
      },
      imgHandleRemove(type, vm) {

        return utils.UPLOAD.Upload().handleRemove(type, vm);
      },
      uploadImg: function (modelName, name) {
        //  使用formdata格式
        let formData = new FormData();
        formData.append("model", modelName);//图片上传子目录
        console.log(formData);
        console.log(this.formData.files[name]);
        if (this.formData.files[name]) {
          formData.append("file", this.formData.files[name]);
        }
        console.log("----------------------------");
        console.log(formData);
        //为什么要封装一下方法 1.每个vue组件有自己的一些参数处理，简化调用本来这个setDataFromAxios这个方法属于api 重新封装就属于当前页面
        api.setDataFromAxios(this.$store.state.host + "/uploadImg", formData, "post", {headers: {"Content-Type": "multipart/form-data"}})
          .then(dto => {
            this.oldImg = false;
            this.$message.info("上传图片成功!");
            if (dto.code == 200) {
              this.restaurant.rimg = dto.obj;
            }
          });//.then方法 就是当服务器有返回的时候执行回调函数，对比jquery的ajax success:function（data）
        //上传图片结束
      },
      uploadFiles(file) {
        //console.log(file.file)
        // console.log("uploadFiles");
        this.formDatas.append('file', file.file);
        this.fileLists.push(file);
      },
      submitUpload() {
        console.log("submitUpload");
        console.log(this.formDatas['file']);
        this.formDatas = new FormData()
        this.$refs.upload.submit(); //执行此步骤 相当于执行 http-request 的自定义实现方法
        this.formDatas.append('model', "restaurant");
        //console.log(this.formData);
        let config = {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        }
        api.setDataFromAxios(this.$store.state.host + "/uploadImg", this.formDatas, "post", config).then(dto => {
          console.log(dto)
          if (dto.code == 200) {
            this.$message.success("上传成功");
            this.fileLists = [];
            let urls = dto.obj.split(",");
            for (let i = 0; i < urls.length; i++) {
              let fileObj = {};
              fileObj.name = "file";
              fileObj.url = this.$store.state.host + "/upload/images/restaurant/" + urls[i];
              console.log(fileObj.url);
              this.fileLists.push(fileObj);
            }
            console.log(dto.obj);
            this.restaurant.rpic = dto.obj;
          } else {
            this.$message.error("上传失败");
          }
        }).catch(res => {
          console.log(res)
        })
      },
      handleRemove(file, fileList) {
        console.log(file, fileList);
        fileList.remove(file);
      },
      handlePreview(file) {

      }
    },
    computed: {
      getUploadUrl() {
        return this.$store.state.host + "/uploadImg";
      }
    },
    //监听
    watch: {
      dialogisShow(newValue, oldValue) {
        this.dialogisShow = newValue;
      }
    }

  }
</script>

<style scoped>

</style>
